﻿// Based on http://www.jebishop.com/2009/11/18/implementing-a-contextmenu-in-silverlight-4-beta/
// Updated by Anvaka
using System.Windows;
using System.Windows.Input;

namespace ContextMenuControls
{
    [TemplateVisualState(Name = StateNormal, GroupName = GroupCommon)]
    [TemplateVisualState(Name = StateActive, GroupName = GroupCommon)]
    public sealed class MenuItem : MenuItemBase
    {
        private const string GroupCommon = "Common";
        private const string StateNormal = "Normal";
        private const string StateActive = "Active";        

        private bool _isActive;

        public MenuItem()
        {
            DefaultStyleKey = typeof(MenuItem);
            _isActive = false;            
        }

        protected override void OnMouseEnter(MouseEventArgs e)
        {
            base.OnMouseEnter(e);
            Focus();
        }

        protected override void OnMouseLeave(MouseEventArgs e)
        {
            base.OnMouseEnter(e);
            _isActive = false;
            UpdateState(true);
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            
            Focus();
        }

        protected override void OnGotFocus(RoutedEventArgs e)
        {
            base.OnGotFocus(e);
            _isActive = true;
            UpdateState(true);
        }

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            base.OnGotFocus(e);
            _isActive = false;
            UpdateState(true);
        }

        private void UpdateState(bool useTransitions)
        {
            if (_isActive)
            {
                VisualStateManager.GoToState(this, StateActive, useTransitions);
            }
            else
            {
                VisualStateManager.GoToState(this, StateNormal, useTransitions);
            }
        }    

      
    }   
}
